#!/bin/bash
###########################################################################
# Copyright 2020 Arista. The term "Arista" refers to Arista Inc.          #
# and/or its subsidiaries.                                                #
#                                                                         #
# Licensed under the Apache License, Version 2.0 (the "License");         #
# you may not use this file except in compliance with the License.        #
# You may obtain a copy of the License at                                 #
#                                                                         #
#   http://www.apache.org/licenses/LICENSE-2.0                            #
#                                                                         #
# Unless required by applicable law or agreed to in writing, software     #
# distributed under the License is distributed on an "AS IS" BASIS,       #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.#
# See the License for the specific language governing permissions and     #
# limitations under the License.                                          #
#                                                                         #
###########################################################################
# SONiC chassis_db configuration                                          #
#                                                                         #
# This script is used to add chassis_db address in local hosts and        #
# indicate to start database-chassis service. It should be excuted before #
# database-chassis.service started.                                       #
#                                                                         #
###########################################################################

config_chassis_db() {
    startdb_file="/etc/sonic/chassisdb.conf"
    [ ! -e $startdb_file ] || rm $startdb_file
    platform=$(sonic-cfggen -H -v DEVICE_METADATA.localhost.platform)
    # database-chassis services will start when $chassis_config file exists
    chassis_config="/usr/share/sonic/device/$platform/chassisdb.conf"
    if [ ! -e $chassis_config ]; then
       echo "no chassisdb.conf found, bypass config-chassisdb service"
       exit 0
    fi
    start_chassis_db=0
    chassis_db_address=""
    source $chassis_config
    if [[ "$start_chassis_db" == "1" ]]; then
       cp $chassis_config $startdb_file
       echo "start chassisdb"
    fi
    if [[ "$start_chassis_db" == "1" ]] || [[ -n "$chassis_db_address" ]]; then
       if [ -z "$chassis_db_address" ]; then
	  echo "no user configured chassisdb address"
       else
          grep redis_chassis /etc/hosts
          if [ $? -ne 0 ]; then
            echo "$chassis_db_address redis_chassis.server" >> /etc/hosts
            echo "update chassis db address to $chassis_db_address"
          fi
       fi
    fi
}

config_chassis_db

exit 0
